package com.bjtu.ptsite.service.impl;

import com.bjtu.ptsite.mapper.PeerMapper;
import com.bjtu.ptsite.mapper.PromotionRuleMapper;
import com.bjtu.ptsite.model.PromotionRule;
import com.bjtu.ptsite.service.PromotionService;
import com.bjtu.ptsite.tracker.entity.TrackerMessage;
import com.bjtu.ptsite.mapper.TrackerMessageMapper;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

// PromotionService 服务类
@Service
@RequiredArgsConstructor
public class PromotionServiceImpl implements PromotionService {
    private final TrackerMessageMapper seedMapper;
    private final PromotionRuleMapper promotionRuleMapper;
    private final PeerMapper peerMapper;

    /**
     * 每分钟检查促销条件并应用规则
     */
    @Scheduled(fixedRate = 60_000)
    @Transactional
    public void applyPromotionRules() {
        // 使用QueryWrapper查询激活的规则
        List<PromotionRule> activeRules = promotionRuleMapper.selectList();

        // 查询所有种子
        List<TrackerMessage> activeSeeds = seedMapper.selectAllTorrents();

        activeSeeds.forEach(seed ->
                activeRules.forEach(rule -> {
                    if (isConditionMet(seed, rule)) {
                        applyAction(seed, rule);
                    }
                })
        );
    }

    public void applyPromotionRules(String infoHash) {
        // 使用QueryWrapper查询激活的规则
        List<PromotionRule> activeRules = promotionRuleMapper.selectList();

        // 查询所有种子
        List<TrackerMessage> activeSeeds = seedMapper.selectByInfoHash2(infoHash);

        activeSeeds.forEach(seed ->
                activeRules.forEach(rule -> {
                    if (isConditionMet(seed, rule)) {
                        applyAction(seed, rule);
                    }
                })
        );
    }

    /**
     * 条件判断逻辑（保持原逻辑不变）
     */
    public boolean isConditionMet(TrackerMessage seed, @NotNull PromotionRule rule) {
        return switch (rule.getConditionType()) {
            case "time" -> isWithin24Hours(seed.getUploadTime(), rule.getThreshold());
            case "seeders" -> {
                // 使用MyBatis-Plus的count查询
                int seeders = peerMapper.selectCount(seed.getInfoHash());
                yield seeders < (rule.getThreshold() != null ? rule.getThreshold() : 10);
            }
            case "holiday" -> checkHoliday();
            default -> false;
        };
    }

    /**
     * 应用促销动作（修改持久化方式）
     */
    public void applyAction(TrackerMessage seed, @NotNull PromotionRule rule) {
        switch (rule.getActionType()) {
            case "free_download":
                seed.setPromotionStatus("FREE_DOWNLOAD");
                seed.setFreeleech(true);
                seed.setDownloadDiscount(String.valueOf(0.0));
                break;
            case "upload_boost":
                seed.setUploadMultiplier(rule.getValue());
                break;
            case "download_discount":
                seed.setDownloadDiscount(String.valueOf(rule.getValue()));
                break;
        }
        // 使用MyBatis-Plus的updateById方法
        seedMapper.updateById(seed);
    }

    // 以下辅助方法保持不变
    public boolean isWithin24Hours(LocalDateTime createTime, Double threshold) {
        if (threshold == null) {
            threshold = 24.0;
        }
        return Duration.between(createTime, LocalDateTime.now()).toHours() <= threshold;
    }

    public boolean checkHoliday() {
        Set<LocalDate> holidays = Set.of(
                // 2025年中国法定节假日（当天日期）
                LocalDate.of(2025, 1, 1),    // 元旦
                LocalDate.of(2025, 1, 29),   // 春节（农历正月初一）
                LocalDate.of(2025, 4, 4),    // 清明节
                LocalDate.of(2025, 5, 1),    // 劳动节
                LocalDate.of(2025, 5, 31),   // 端午节（农历五月初五）
                LocalDate.of(2025, 9, 7),    // 中秋节（农历八月十五）
                LocalDate.of(2025, 10, 1)    // 国庆节
        );
        return holidays.contains(LocalDate.now());
    }
}//This is a comment
